# protocol stat all

require "dbm"
require "00_common"



module ProtocolAggre
  def self.get_all_protocol_stat_files
  	Common.get_all_files "./stat_protol"
  end

  def self.aggregate_all_files(all_files)
  	all_mapping = Hash.new
  	all_files.each do |file_name|
      one_mapping = get_one_mapping(file_name)
      one_mapping.each do |key, value|
      	domain = Common.extract_domain(key)
      	# puts domain
      	if all_mapping[domain]
      	  all_mapping[domain] = all_mapping[domain] + value
      	else
      	  all_mapping[domain] = value
      	end
      end
  	end

  	all_mapping
  end

  def self.get_one_mapping(file_name)
  	file = File.open "./stat_protol/" + file_name, "r"
  	one_mapping = Hash.new
  	begin
  	  while line = file.readline
  	  	fields = line.split "|"
  	  	key = fields[0]
  	  	value = fields[1].to_i

  	  	one_mapping[key] = value
  	  end
  	rescue Exception => e
  	  # puts e.to_s
  	  file.close
  	end

  	one_mapping
  end

  def self.output_all_mapping(all_mapping)
  	output_file = File.open "protocol_stat_all.csv", "w"
  	all_mapping.each do |key,value|  
  	  output_file.puts "#{key},#{value}"
  	end
  	output_file.close
  end
end

begin
  all_files = ProtocolAggre.get_all_protocol_stat_files
  puts all_files.join "\n"

  puts "---------"

  all_mapping = ProtocolAggre.aggregate_all_files all_files
  ProtocolAggre.output_all_mapping all_mapping
rescue Exception => e
  puts "ERROR:" + e.to_s 
end